<template>
  <div>
    <a-modal
      title="授权"
      width="900px"
      :visible="visible"
      :confirm-loading="confirmLoading"
      destroy-on-close
      @cancel="handleClose"
    >
      <a-form-model
        ref="ruleFormModel"
        :model="formModel"
        :rules="rulesModel"
        :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
        style="padding-right: 60px"
      >
        <a-row :gutter="24">
          <a-col span="18">
            <a-form-model-item
              label="单点域"
              prop="domainId"
            >
              <a-select
                v-model="formModel.domainId"
                placeholder="请填写正确的内容"
              >
                <a-select-option
                  v-for="item in domainList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{
                    item.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col span="6">
            <a-form-model-item>
              <a-button
                type="primary"
                icon="search"
                class="mr20"
                style="vertical-align: middle"
                @click="handleSearchRole"
              >
                查询
              </a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <a-spin :spinning="loading">
        <a-transfer
          style="display: flex; justify-content: center; align-items: center"
          :list-style="{ width: '300px', height: '300px' }"
          :titles="['可授权角色', '已授权角色']"
          :operations="['授权', '移除']"
          show-search
          :data-source="dataSource"
          :target-keys="targetKeys"
          :row-key="(record) => record.key"
          :render="(item) => `${item.title}`"
          @change="handleChange"
        />
      </a-spin>
      <template slot="footer">
        <a-button
          key="back"
          @click="handleClose"
        >
          取消
        </a-button>
        <a-button
          key="submit"
          type="primary"
          @click="visiblePsw = true"
        >
          确认
        </a-button>
      </template>
    </a-modal>
    <a-modal
      title="二次授权"
      :visible="visiblePsw"
      @cancel="handleCancelJuri"
    >
      <a-form-model
        ref="ruleFormInlineModel"
        :model="formInline"
        :rules="ruleFormInline"
        :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-form-model-item
          label="密码"
          prop="password"
        >
          <BaseInput
            v-model="formInline.password"
            type="password"
            placeholder="请输入正确的密码"
          />
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button
          key="back"
          @click="handleCancelJuri"
        >
          取消
        </a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="confirmLoading"
          @click="handleSubmitUser"
        >
          确认
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import {
    getPointDomains,
    addRoleList,
    editRoleList,
    getJurisdictionUserid,
    getJurisdictionDomainId,
    SaveWithSecondEmpower
} from '@/api/system/system'
import { PublicKey } from '@/config'
export default {
    name: 'JurisdictionUpdate',
    props: {
        visible: {
            type: Boolean,
            default: () => false
        },
        record: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        return {
            loading: false,
            rulesModel: {
                domainId: [{ required: true, message: '请输入正确的内容', trigger: 'blur' }]
            },
            ruleFormInline: {
                password: [{ required: true, message: '请输入正确的内容', trigger: 'blur' }]
            },
            confirmLoading: false,
            domainList: [],
            formModel: {
                domainId: undefined
            },
            dataSource: [],
            targetKeys: [],
            originKeys: [], // 存储原本所拥有的角色key值
            visiblePsw: false,
            formInline: {
                password: ''
            },

            links: []
        }
    },
    watch: {
        visible: {
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.getPointDomains()
                    })
                }
            }
        }
    },
    mounted() {
        //
        // this.getMock();
    },

    methods: {
        /**
         *@desc 单点域列表 获取
         *@param {}
         */
        getPointDomains() {
            getPointDomains()
                .then((res) => {
                    if (res.status === 200) {
                        //单点域获取成功
                        this.domainList = res.data
                        //默认选中单点域
                        console.log(this.domainList)
                        this.formModel.domainId = this.domainList[0].id
                        this.$nextTick(() => {
                            this.handleSearchRole()
                        })
                    }
                })
                .catch((err) => {
                    console.log(err)
                })
        },
        /**
         *@desc 根据单点域查询列表
         *@param {}
         */
        handleSearchRole() {
            this.$refs.ruleFormModel.validate((valid) => {
                if (valid) {
                    this.loading = true
                    // this.getJurisdictionDomainId()
                    this.getJurisdictionUserid()
                } else {
                    return false
                }
            })
        },
        /**
         *@desc 重置表单
         *@param {}
         */
        handleReset() {
            this.$refs.ruleFormModel.resetFields()
        },
        handleClose() {
            this.dataSource = []
            this.targetKeys = []
            this.handleReset()
            this.$emit('handleCancel')
        },
        /**
         *@desc 提交权限修改 密码二次授权
         *@param {}
         */

        getJurisdictionUserid() {
            getJurisdictionUserid({ userId: this.record.id })
                .then((res) => {
                    let data = res.data
                    if (res.status === 200) {
                        //获取成功
                        this.targetKeys = data.map((item) => {
                            return item.id
                        })
                        this.originKeys = [...this.targetKeys] // 备份，提交时用来做比对
                        this.getJurisdictionDomainId()
                    } else {
                        //获取失败
                    }
                })
                .catch((err) => {
                    //验证失败
                })
        },
        getJurisdictionDomainId() {
            getJurisdictionDomainId({ domainId: this.formModel.domainId })
                .then((res) => {
                    if (res.status === 200) {
                        //获取成功
                        this.loading = false
                        this.dataSource = res.data.map((item) => {
                          //标记下是否右边
                           item.isRight = false
                           //右边不禁用
                            if(this.targetKeys.includes(item.id)) {
                              item.isRight = true
                            }
                            return { key: item.id, title: item.name, disabled: !item.enable&&!item.isRight, isRight: item.isRight}
                        })
                    } else {
                        this.loading = false
                        //获取失败
                    }
                })
                .catch((err) => {
                    //验证失败
                    this.loading = false
                })
        },

        filterOption(inputValue, option) {
            return option.description.indexOf(inputValue) > -1
        },
        handleChange(targetKeys, direction, moveKeys) {
            // targetKeys：显示在右侧框数据的 key 集合
            // moveKeys：移动数据的 key 集合
          this.targetKeys = targetKeys
          this.dataSource.forEach(item=>{
            if(!this.targetKeys.includes(item.id)) {
              if(item.isRight) {
                item.disabled = !item.enable
                item.isRight = false
              }
            }
          })
          let flag = false
            if (direction === 'right') {
                flag = false
            } else if (direction === 'left') {
                flag = true
            }
            let links = []
            targetKeys.map((item) => {
                links.push({ domainId: this.formModel.domainId, flag: flag, roleId: item })
            })
            this.links = links
        },
        /**
         *@desc 提交权限修改 密码二次授权
         *@param {}
         */
        handleSubmitUser() {
            this.$refs.ruleFormInlineModel.validate((valid) => {
                if (valid) {
                    const removeList = this.originKeys
                        .filter((item) => {
                            return !this.targetKeys.includes(item)
                        })
                        .map((id) => {
                            return {
                                domainId: this.formModel.domainId,
                                flag: true,
                                roleId: id
                            }
                        })
                    const addList = this.targetKeys
                        .filter((item) => {
                            return !this.originKeys.includes(item)
                        })
                        .map((id) => {
                            return {
                                domainId: this.formModel.domainId,
                                flag: false,
                                roleId: id
                            }
                        })
                    // 获取变更的角色列表
                    const allList = addList.concat(removeList)
                    if (!allList.length) {
                        this.$message.warning('未变更角色')
                        return
                    }
                    let params = {
                        userId: this.record.id,
                        links: allList,
                        pscode: this.doSm3AndSm2Encrypt(this.formInline.password)
                    }
                    this.confirmLoading = true
                    SaveWithSecondEmpower(params)
                        .then((res) => {
                            this.confirmLoading = false
                            this.handleCancelJuri()
                            this.$message.success(res.data.message)
                            this.handleClose()
                        })
                        .catch((err) => {
                            this.confirmLoading = false
                            // 避免和请求拦截器的错误提示冲突,因此这里过滤掉该种情况的提示
                            if (err.code !== '非法的用户') {
                                this.$message.error(err.message || '请求失败，请稍后重试！')
                            }
                        })
                } else {
                    this.$message.error('表单验证失败！请输入正确的内容。')
                    //验证失败
                }
            })
        },

        // handleSearchTransfer(dir, value) {
        //   console.log('search:', dir, value);
        // },
        handleCancelJuri() {
            this.visiblePsw = false
            this.handleResetJus()
        },
        /**
         *@desc 重置表单
         *@param {}
         */
        handleResetJus() {
            this.$refs.ruleFormInlineModel.resetFields()
        },
        /**
         *@desc 密码加密
         *eslint-disable
         */
        doSm3AndSm2Encrypt(sourceStr) {
            const sm2Utils = new Sm2Utils()
            const public_key = PublicKey
            const sm3_random_plain =
                Sm3Utils.encryptFromText(sourceStr) + '|' + sm2Utils.randomWord(8) + '|' + sourceStr
            const sm3_sm2_plain = sm2Utils.encryptFromText(public_key, sm3_random_plain)
            return '{crypto}' + sm3_sm2_plain
            /* eslint-enable */
        }
    }
}
</script>

<style scoped>
</style>
